<template>
  <div class="container">
    <div class="export-box">
      <!-- <el-button v-if="type=='tc'" type="primary" @click="exportImg">导出为图片</el-button> -->
      <div v-if="type=='gh'">
        <el-button type="primary" @click="exportPdf">导出为PDF</el-button>
        <el-button type="primary" @click="savePlan">保存</el-button>
        <el-button  v-if="typeFx=='fx'" type="primary" @click="sharePlan">分享</el-button>
    </div>
    <!-- <div style="padding: 10px">
          背景色：<el-color-picker v-model="style.background" size="small"></el-color-picker>&nbsp;
          文字颜色：<el-color-picker v-model="style.color" size="small"></el-color-picker>&nbsp;
    </div> -->
    </div>
    <div class="pdf-panel">
<!-- <pdfModle ref="pdf" class="pdfRef" :data="{}" id="pdfDom"/> -->

    </div>
    <div class="pdfContent">

      <vue3-tree-org @on-node-click="onNodeClick" :define-menus="defineMenus" class="pdfRef" :label-style="style" style="width: 97vw; height: 80vh;background-color:rgba(255,255,255,0)"  @on-expand-all="onExpandAll" ref="treeRef" :disabled="disabled"  :default-expand-level="defaultExpandLevel" :data="data" :horizontal="horizontal" :collapsable="collapsable" @on-contextmenu="onContextmenu"/>
    </div>
    <div class="pdf-header"
            style="font-weight: bold; padding:15px 8px; width: 100%; border-bottom: 1px solid rgba(0, 0, 0, 0.85); color: rgba(0, 0, 0, 0.85); position: fixed; top: -100vh;">
            页头
        </div>
        <div class="pdf-footer"
            style="font-weight: bold; padding: 15px 8px; width: 100%; border-top: 1px solid rgba(0, 0, 0, 0.85); position: fixed; top: -100vh;">
            <div style="display: flex; justify-content: center; align-items: center; padding-top: 5px;">
                我是页尾
            </div>
            <div style="display: flex; justify-content: center; align-items: center; margin-top: 20px;">
                第<div class="pdf-footer-page"></div>页 / 第<div class="pdf-footer-page-count"></div>页
            </div>
        </div>
    <el-dialog
      v-model="shareDialog"
      align-center
      title="分享您的规划结果"
      width="600"
    >
      <div class="flex">
        <el-input v-model="shareLink" disabled />
        <el-button @click="copyLink">复制链接</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElSwitch, ElColorPicker, ElMessage } from 'element-plus'
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import { dataTool } from "echarts/core";
import { styleType } from "element-plus/es/components/table-v2/src/common";
import { copyText } from "../../utils/copyText"
import { savePlanDetail } from "../../service/matching/";
import { useSearchStore } from "../../store/search";

// import infoCard from "../../components/infoCard/index.vue";
// import pdfModle from '../PDFModle/index.vue'

const pdfData = JSON.parse(localStorage.getItem('pdfData'))
const store = useSearchStore();
import {exportWord} from '../../utils/pdf'

const exportPdf = async ()=>{
    // var fileName= '投资评审报告'
	  // const fileList = document.getElementsByClassName('pdfRef')   // 很重要
	  // htmlPdf(fileName,document.querySelector('#pdfRef'),fileList,'a4')
    // outputPDF.getPdf('周期报告');
    // const element = document.querySelector('.pdf-panel');
    //   const header = document.querySelector('.pdf-header');
    //   const footer = document.querySelector('.pdf-footer');
      // const fileUrl = new URL(`../../../public/word.docx`, import.meta.url).href
      // ExportBriefDataDocx(fileUrl, {}, 'ces'+'.docx')
      exportWord(pdfData,pdfData.company.companyNameList[0]+'.docx')
      // try {
      //   await outputPDF({
      //     element: element,
      //     footer: footer,
      //     header: header,
      //     contentWidth: 560
      //   })
      // } catch (error) {
      //   // message.error(typeof error === 'string' ? error : JSON.stringify(error))
      // }

}

import { da } from "element-plus/es/locale";
const shareLink = ref(window.location.href)
const treeRef = ref(null);

const props = defineProps({data:{type:Object,default:{}},
                            horizontal:{type:Boolean,default:true},
                            collapsable:{type:Boolean,default:true},
                            disabled:{type:Boolean,default:true},
                            title:{type:String,default:'图谱'},
                            defaultExpandLevel:{type:Number,default:100},
                            type:{type:String,default:'tc'},typeFx:{type:String,default:''},
                            companyID:{type:String,default:''},
                            form:{type:Object,default:{}},
                            seachType:{type:String,default:''},
                            });
const style = ref({
        background: "#409eff",
        color: "#ffff",
      })

  const shareDialog = ref(false)
    const sharePlan = () => {
    shareDialog.value = !shareDialog.value
  }
    const copyLink = () => {
    copyText(shareLink.value)
  }
  const onNodeClick = (e,data)=>{
    if(data.id==0) return
    const url = window.location.host;
    window.open('http://'+url+`/detail?id=${data.id}&searchType=`+props.seachType)
  }
  const defineMenus = (e, node)=> {
    console.log(e,node.id)
    if(node.id!='1000001'||node.id!=='1000002'||node.id!=='1000003'||node.id!=='1000004')
       return [ { name:'删除', command: 'delete' },]
    }
const filterDate = (val:any,id:String)=>{
  return val.filter((el:any) => {
    if(el.id==id){
      return false
    }
    else if(el.children){
      el.children = filterDate(el.children,id)
      return true
    }else{
      return true
    }
  });
}
  const savePlan = async () => {
    try {
      const params = {
        id: localStorage.getItem('savePlanId'),
        companyId: props.companyID,
        companyName: props.form.keyword,
        revenueScale: props.form.price,
        content: JSON.stringify(props.data.children || [])
      };

      // send request
      const result = await savePlanDetail(params);
      // store.savePlanId = result.data
      localStorage.setItem("savePlanId", result.data)
      // isHandle.value = true
      // showSaveBtn.value = false
      if (result.code == 200) {
        ElNotification({
          title: "保存成功",
          message: "可在我的规划中查看",
          type: "success"
        });
      } else {
        ElNotification({
          title: "保存失败",
          message: "请联系管理员处理",
          type: "error"
        });
      }

    } catch (error) {
      ElNotification({
        title: "保存失败",
        message: "请联系管理员处理",
        type: "error"
      });
    }
  };
const onContextmenu = (command:any,node:any)=>{
  if(command.command=='delete'){

     filterDate(props.data.children,command.data.id)
     console.log(props.data.children)
  }
  // console.log(command,node,'=======',command.data.children)
  // if(command.command=='copy'&&!command.data.children){
  //   ElMessage('不能删除父节点')
  // }
}

// const exportImg = async()=>{
// try {
//    // 使用html2canvas将DOM转换为Canvas
//     const canvas = await html2canvas(treeRef.value.$el);
//     // 将Canvas转换为图片数据
//     const imgData = canvas.toDataURL('image/png');
//     // 创建一个新的jsPDF实例
//       const pdf = new jsPDF('p', 'mm', 'a4')
//       // 计算图片在PDF中的宽度和高度
//       const imgProps = pdf.getImageProperties(imgData);
//       const pdfWidth = pdf.internal.pageSize.getWidth();
//       const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;

//     let save  = document.createElement('a');
//     save.href = imgData;
//     // 下载的名字
//     save.download = props.title
//     // 直接回调a的点击事件
//     save.click()
//   } catch (error) {
//     console.error('导出图片失败:', error);
//   }
// }
const onExpandAll = (isExpandAll:boolean)=>{
}
// 水印
const addWatermark = (canvas, text) => {
  const ctx: any = canvas.getContext('2d');
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.rotate((20 * Math.PI) / 180);
  ctx.font = '20px Microsoft Yahei';
  ctx.fillStyle = 'rgba(184, 184, 184, 0.8)';
  console.log(canvas.width)
  console.log(canvas.height)

  for (let i = canvas.width * -1; i < canvas.width; i += 240) {
    for (let j = canvas.height * -1; j < canvas.height; j += 200) {
      // 填充文字，x 间距, y 间距
      ctx.fillText('透策', i, j);
    }
  }
    };

    const exportImg = async () => {
      try {
        const node = treeRef.value.$el;
        const canvas = await html2canvas(node);
        console.log('canvas',canvas)
        addWatermark(canvas, '透策');
        const img = canvas.toDataURL('image/png');
        const a = document.createElement('a');
        a.href = img;
        a.download = props.title;
        a.click();
      } catch (error) {
        console.error('Error exporting tree as image:', error);
      }
    };

var noTableHeight = 0 //table外的元素高度

const htmlPdf = (title, html, fileList, type) => {// type传有效值pdf则为横版
  if (fileList) {
    const pageHeight = Math.floor(277 * html.scrollWidth / 190) + 20 //计算pdf高度
    for (let i = 0; i < fileList.length; i++) { //循环获取的元素
      const multiple = Math.ceil((fileList[i].offsetTop + fileList[i].offsetHeight) / pageHeight) //元素的高度
      if (isSplit(fileList, i, multiple * pageHeight)) { //计算是否超出一页
        var _H = '' //向pdf插入空白块的内容高度
        if (fileList[i].localName !== 'tr') { //判断是不是表格里的内容
          _H = multiple * pageHeight - (fileList[i].offsetTop + fileList[i].offsetHeight)
        } else {
          _H = multiple * pageHeight - (fileList[i].offsetTop + fileList[i].offsetHeight + noTableHeight) + 20
        }
        var newNode = getFooterElement(_H)  //向pdf插入空白块的内容
        const divParent = fileList[i].parentNode // 获取该div的父节点
        const next = fileList[i].nextSibling // 获取div的下一个兄弟节点
        // 判断兄弟节点是否存在
        if (next) {
          // 存在则将新节点插入到div的下一个兄弟节点之前，即div之后
          divParent.insertBefore(newNode, next)
        } else {
          // 否则向节点添加最后一个子节点
          divParent.appendChild(newNode)
        }
      }
    }
  }
  html2canvas(html, {
    allowTaint: false,
    taintTest: false,
    logging: false,
    useCORS: true,
    dpi: window.devicePixelRatio * 1,
    scale: 1 // 按比例增加分辨率
  }).then(canvas => {
    var pdf = new jsPDF('p', 'mm', 'a4') // A4纸，纵向
    addWatermark(canvas, '透策');
    var ctx = canvas.getContext('2d')
    var a4w = type ? 277 : 190; var a4h = type ? 190 : 277 // A4大小，210mm x 297mm，四边各保留10mm的边距，显示区域190x277
    var imgHeight = Math.floor(a4h * canvas.width / a4w) // 按A4显示比例换算一页图像的像素高度
    var renderedHeight = 0
    while (renderedHeight < canvas.height) {
      var page = document.createElement('canvas')
      page.width = canvas.width
      page.height = Math.min(imgHeight, canvas.height - renderedHeight)// 可能内容不足一页

      // 用getImageData剪裁指定区域，并画到前面创建的canvas对象中
      page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0)
      pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width)) // 添加图像到页面，保留10mm边距

      renderedHeight += imgHeight
      if (renderedHeight < canvas.height) {
        pdf.addPage()// 如果后面还有内容，添加一个空页
      }
      // delete page;
    }
    // 保存文件
    pdf.save(title + '.pdf')
  })
}
// pdf截断需要一个空白位置来补充
const getFooterElement = (remainingHeight, fillingHeight = 0) => {
  const newNode = document.createElement('div')
  newNode.style.background = '#ffffff'
  newNode.style.width = 'calc(100% + 8px)'
  newNode.style.marginLeft = '-4px'
  newNode.style.marginBottom = '0px'
  newNode.classList.add('divRemove')
  newNode.style.height = (remainingHeight + fillingHeight) + 'px'
  return newNode
}
const isSplit = (nodes, index, pageHeight) => {
  // 判断是不是tr 如果不是高度存起来
  // 表格里的内容要特殊处理
  // tr.offsetTop 是tr到table表格的高度
  // 所以计算高速时候要把表格外的高度加起来
  // 生成的pdf没有表格了这里可以不做处理 直接计算就行
  if (nodes[index].localName !== 'tr') {  //判断元素是不是tr
    noTableHeight += nodes[index].clientHeight
  }

  if (nodes[index].localName !== 'tr') {
    return nodes[index].offsetTop + nodes[index].offsetHeight < pageHeight && nodes[index + 1] && nodes[index + 1].offsetTop + nodes[index + 1].offsetHeight > pageHeight
  } else {
    return nodes[index].offsetTop + nodes[index].offsetHeight + noTableHeight < pageHeight && nodes[index + 1] && nodes[index + 1].offsetTop + nodes[index + 1].offsetHeight + noTableHeight > pageHeight
  }
}
const pdf = ref()
// const exportPdf = ()=>{

//   console.log(pdf.value)
//   window.document.body.innerHTML = pdf.value
//   window.print()
//   // var fileName= '投资评审报告'
// 	//   const fileList = document.getElementsByClassName('pdfRef')   // 很重要
// 	//   htmlPdf(fileName, document.querySelector('#pdfRef'), fileList)
// }
</script>

<style lang="postcss">
.pdfContent{
  height: 100vh;
   display: flex;
  justify-content: center;
  align-items: center;
}
.container{
  /* height: 80vh; */
   position: relative;
   .export-box{
    /* position: absolute;
    top: 10px;
    left: 10px; */
    z-index:99999
   }
}
/* 覆盖节点的背景颜色 */
.tree-org-node__text {
  border:1px solid #419DFF;
  border-radius: 5px;
  /* color: #419DFF; */
}
.tree-org-node:not(:only-child):after{
  border-top: 1px solid #419DFF;
}
.tree-org-node:not(:first-child):before, .horizontal .tree-org-node:not(:last-child):after{
  border-left: 1px solid #419DFF;
}
tree-org-node:not(:first-child):before, .horizontal .tree-org-node:not(:last-child):after{
  border-left: 1px solid #419DFF;

}
.horizontal .tree-org-node:not(:first-child):before, .horizontal .tree-org-node:not(:last-child):after{
  border-left: 1px solid #419DFF;
}
.horizontal .tree-org-node:not(:only-child):after{
  border-top: 1px solid #419DFF;
}
.tree-org-node__expand{
  border: 1px solid #419DFF;
}
.tree-org-node__expand .tree-org-node__expand-btn:before{
  border-top: 1px solid #419DFF;
}
.tree-org-node__expand .tree-org-node__expand-btn:after{
  border-left: 1px solid #419DFF;
}
/* .horizontal .tree-org-node__children:before{
  border-top: 1px solid #419DFF;
} */
</style>
